<template>
  <a-modal v-model:visible="modalVisible">
    <template #title> {{ props.title }} </template>
    <template #footer>
      <a-space>
        <a-button type="primary" @click="handleOk">确定</a-button>
        <a-button @click="modalVisible = false">取消</a-button>
      </a-space>
    </template>
    <div>
      <a-form :model="form" auto-label-width :rules="rules" ref="formRef">
        <a-form-item field="roleName" label="角色名称：">
          <!-- <a-input
            placeholder="请输入角色名称"
            v-model="form.roleName"
            allow-clear
          ></a-input> -->
          <a-input v-model="form.roleName" allow-clear />
          <!-- <a-cascader
            :field-names="fieldNames"
            v-model="form.parentId"
            :options="GetMenuData"
            check-strictly
          /> -->
        </a-form-item>
        <a-form-item
          tooltip="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
          label="权限字符："
        >
          <a-input allow-clear />
        </a-form-item>
        <a-form-item label="角色顺序：">
          <a-input-number
            :min="1"
            placeholder="Please Enter"
            :default-value="1"
            mode="button"
            v-model="form.roleSort"
          />
        </a-form-item>
        <a-form-item field="roleCode" label="状态：">
          <a-radio-group v-model="form.status">
            <a-radio :value="1">启用</a-radio>
            <a-radio :value="2">停用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item field="menuIds" label="菜单名称：">
          <a-tree
            :checkable="true"
            checked-strategy="all"
            v-model:checked-keys="form.menuIds"
            :check-strictly="checkStrictly"
            :field-names="{
              key: 'menuId',
              title: 'menuName',
              children: 'node',
            }"
            :data="getRoleTree"
            @check="getSelectedNodes"
          />
        </a-form-item>
        <a-form-item
          tooltip="访问的路由地址，如：`user`，如外网地址需内链访问则以`http(s)://`开头"
          label="备注："
        >
          <a-textarea
            v-model="form.remarks"
            placeholder="Please enter something"
            allow-clear
          />
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { reactive, computed, ref, watchEffect, nextTick } from 'vue';
  import { GetRouters } from '@/api/menu';
  // import { cloneDeep } f rom 'lodash';

  const formRef = ref();
  const props = withDefaults(
    defineProps<{
      formList: any;
      title: string;
      visible: boolean;
    }>(),
    {
      visible: false,
    }
  );
  let form = ref<any>({});

  const validateMenuIds = (val: any, callback: any) => {
    if (!val.length) callback(new Error('菜单不能为空!'));
    return true;
  };

  const rules = reactive({
    roleName: [{ required: true, message: '角色名称' }],
    menuIds: [{ required: true, validator: validateMenuIds }],
  });

  const emit = defineEmits(['update:visible', 'addRoleEmit']);
  const getRoleTree = ref<any>([]);

  //   const data = (list) => {
  //     list.forEach((item) => {
  //       if(item.node && item.node.length){
  // data
  //       }else{
  //         item.node = []
  //       }
  //     });
  //   };
  const checkedKeys = ref([]);
  const checkStrictly = ref(false);
  const GetRoleData = async () => {
    try {
      const res = await GetRouters();
      let replaceStr = JSON.parse(
        JSON.stringify(res).replace(/"icon"/g, '"icons"')
      );
      getRoleTree.value = replaceStr;
    } catch (error: unknown) {
      console.log(error);
    }
  };
  GetRoleData();

  // 判断用户是否显示弹出框
  const modalVisible = computed({
    get() {
      return props.visible;
    },
    set(visible: boolean) {
      emit('update:visible', visible);
    },
  });

  // 确定
  const handleOk = async () => {
    if (props.title === '新建角色') {
      formRef.value.validate((res: any) => {
        if (!res) {
          emit('addRoleEmit', form.value, 'add');
          modalVisible.value = false;
        } else {
          modalVisible.value = true;
        }
      });
    } else {
      formRef.value.validate((res: any) => {
        if (!res) {
          emit('addRoleEmit', form.value, 'edit');
          modalVisible.value = false;
        } else {
          modalVisible.value = true;
        }
      });
    }
    modalVisible.value = false;
  };

  // 取消
  const handleCancel = () => {
    modalVisible.value = false;
  };

  watchEffect(() => {
    if (modalVisible.value) {
      form.value = props.formList;
    }
  });
</script>

<style scoped lang="less">
  .demo-basic {
    margin-top: 5px;
    width: 500px;
    // margin: auto;
    background-color: aliceblue;
  }
</style>
